<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="1200px"
    :before-close="handleClose"
  >
    <div class="workTitle work">
      <div class="col col1">预览图</div>
      <div class="col col2">作品信息</div>
      <div class="col col3">购买模式</div>
      <div class="col col4">价格</div>
    </div>
    <div class="workWrap">
      <div class="workInfo work">
        <div class="col col1"><img :src="info.image_url" alt="" /></div>
        <div class="col col2">
          <div class="title">{{ info.title_cn }}</div>
          <p>编号：{{ info.image_sn }}</p>
          <p>参数：{{ info.image_dpi }}</p>
          <p>格式：{{ info.image_format }}</p>
          <p>颜色模式：RGB</p>
          <!-- <p>摄影师：Abdullah</p> -->
        </div>
        <div class="col col3">普通授权</div>
        <div class="col col4">￥{{ info.price_cn }}</div>
      </div>
      <div class="tips">
        在确定购买前请确认作品信息的合理性，包括不限于
        <span> 作品格式，软件版本</span>
        等信息
      </div>
      <div class="contact">
        <div class="left">
          <div class="title">CONTACT US</div>
          <div class="text">*有任何支付问题请联系在线客服：400-4000-400</div>
          <ul v-if="isWechat">
            <li>
              <el-button type="success" @click="generateOrderWx"
                >微信支付</el-button
              >
            </li>
          </ul>
          <ul v-else>
            <li>
              <p class="pay1"><img src="@/assets/alipay.png" alt="" />支付宝</p>
            </li>
            <li>
              <p class="pay1"><img src="@/assets/wxpay.png" alt="" />微 信</p>
            </li>
            <!--            <li>-->
            <!--              <p class="pay2">-->
            <!--                <img src="@/assets/payicon3.png" alt="" />Paypal-->
            <!--              </p>-->
            <!--            </li>-->
            <!--            <li>-->
            <!--              <p class="pay2">-->
            <!--                <img src="@/assets/payicon4.png" alt="" />银行卡支付-->
            <!--              </p>-->
            <!--            </li>-->
          </ul>
        </div>
        <div class="right" v-if="!isWechat">
          <div class="aliPay payCode">
            <img :src="qrcode_alipay" alt="" />
            <p><img src="@/assets/alipay.png" alt="" />请用支付宝扫码支付</p>
          </div>
          <div class="wxPay payCode">
            <img :src="qrcode_wxpay" alt="" />
            <p>
              <img src="@/assets/wxpay.png" alt="" />
              请用微信扫码支付
            </p>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "payment",
  data() {
    return {
      dialogVisible: false,
      info: {},
      order_no: "",
      qrcode_wxpay: "",
      qrcode_alipay: "",
      timer: null,
    };
  },
  props: {
    isWechat: {
      type: Boolean,
      validator: (value) => {
        // 确保值是布尔类型（可选，增强健壮性）
        return typeof value === "boolean";
      },
    },
  },
  methods: {
    open(id) {
      this.dialogVisible = true;
      this.getInfo(id);
    },
    getInfo(id) {
      this.$post("/index/images_detail", { image_id: id }).then((res) => {
        this.info = res.data;
        if (!this.isWechat) {
          this.generateOrder(res.data.image_sn);
        }
      });
    },
    generateOrderWx() {
      this.$post("/order/place_order", {
        image_sn: this.info.image_sn,
        isWechat: this.isWechat ? "Y" : "N",
      }).then((res) => {
        console.log(res);
        if (res.code === 1) {
          this.handlePay(res.data);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    generateOrder(image_sn) {
      this.$post("/order/place_order", {
        image_sn: image_sn,
        isWechat: this.isWechat ? "Y" : "N",
      }).then((res) => {
        this.order_no = res.data.order_no;
        this.qrcode_wxpay = res.data.qrcode.wxpay;
        this.qrcode_alipay = res.data.qrcode.alipay;
        this.timer = setInterval(() => {
          this.queryOrder();
        }, 3000);
      });
    },
    queryOrder() {
      let that = this;
      this.$post("/order/query_order", {
        order_no: this.order_no,
      }).then((res) => {
        if (res.data.order_status == "paid") {
          that.handleClose();
          that.$message.success("支付成功");
        }
      });
    },
    handleClose() {
      clearInterval(this.timer);
      this.dialogVisible = false;
    },
    /**
     * 触发微信支付
     */
    async handlePay(payParams) {
      this.loading = true;
      try {
        await this.callWeChatPay(payParams);
      } catch (error) {
        await this.$alert(error.message, "支付失败", {
          confirmButtonText: "重试",
        });
        this.loading = false;
      }
    },

    /**
     * 核心：调用微信 JSAPI 支付
     * @param {Object} payParams - 后端返回的支付参数
     */
    callWeChatPay(payParams) {
      return new Promise((resolve, reject) => {
        // 微信内置对象 WeixinJSBridge：需等待加载完成
        const invokePay = () => {
          WeixinJSBridge.invoke(
            "getBrandWCPayRequest",
            {
              appId: payParams.appId, // 公众号 appId
              timeStamp: payParams.timeStamp, // 10位字符串时间戳（不可转数字）
              nonceStr: payParams.nonceStr, // 随机字符串
              package: payParams.package, // 预支付单：prepay_id=xxx
              signType: payParams.signType, // 签名类型（MD5/HMAC-SHA256）
              paySign: payParams.paySign, // 支付签名（后端生成）
            },
            async (res) => {
              this.loading = false;
              // 微信支付回调结果处理
              switch (res.err_msg) {
                case "get_brand_wcpay_request:ok":
                  this.queryOrder();
                  resolve(true);
                  break;
                case "get_brand_wcpay_request:cancel":
                  this.$alert("你已取消支付", "提示");
                  resolve(false);
                  break;
                default:
                  // 支付失败（签名错误、权限不足等）
                  reject(new Error(`支付失败：${res.err_msg}`));
                  break;
              }
            }
          );
        };

        // 处理 WeixinJSBridge 加载状态
        if (typeof WeixinJSBridge === "undefined") {
          // 未加载完成：监听初始化事件
          document.addEventListener("WeixinJSBridgeReady", invokePay, false);
        } else {
          // 已加载完成：直接调用
          invokePay();
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
:deep .el-dialog__header {
  padding: 0;
}
:deep .el-dialog__body {
  color: #333;
  font-size: 16px;
  padding: 0;
}
.workTitle {
  background: #f6f6f6;
  padding: 20px 50px;
  .col {
    font-weight: bold;
    font-size: 24px;
    text-align: center;
  }
  .col1,
  .col2 {
    text-align: left;
  }
}
.workWrap {
  padding: 30px 50px;
}
.work {
  display: flex;
  align-items: center;
  .col1 {
    width: 25%;
  }
  .col2 {
    width: 35%;
    padding: 0 30px;
  }
  .col3 {
    width: 20%;
    text-align: center;
  }
  .col4 {
    width: 20%;
    text-align: center;
  }
  .title {
    font-weight: bold;
    font-size: 22px;
    margin-bottom: 20px;
  }
}
.tips {
  margin: 30px 0;
  padding: 20px;
  text-align: center;
  background: #ece7ee;
  span {
    font-weight: bold;
    color: #441054;
  }
}
.contact {
  padding: 30px;
  background: #f6f7f9;
  display: flex;
  .left,
  .right {
    width: 50%;
  }
  .left {
    .title {
      font-size: 30px;
      font-weight: bold;
    }
    ul {
      display: flex;
      flex-wrap: wrap;
      li {
        width: 50%;
        padding: 10px;
        p {
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 6px;
          padding: 8px;
        }
        .pay1 {
          border: 1px solid #333;
        }
        .pay2 {
          background: #917bbd;
          color: #fff;
        }
        img {
          display: block;
          width: 38px;
          height: 38px;
          margin-right: 10px;
        }
      }
    }
  }
  .right {
    display: flex;
    .payCode {
      padding: 0 15px;
      width: 50%;
      text-align: center;
      p {
        display: flex;
        align-items: center;
        justify-content: center;
        img {
          width: 38px;
          height: 38px;
        }
      }
    }
  }
}
@media screen and (max-width: 1200px) {
}
@media screen and (max-width: 768px) {
}
</style>
